#ifndef CLOG_H
#define CLOG_H

/*
文件夹存放日志，按时间命名，大于1024 * 1024 * 4 ，(4M)自动新建文件；大小可以根据具体项目更改.
日志信息格式：  [时间][文件名-行号][level]: 信息
使用示例如下：
#include "mainwindow.h"
#include <QApplication>
#include "clog.h"
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    //初始化
    CLog::InstallLog();
    MainWindow w;
    w.show();
    //使用如下
    qDebug() << "test qDebug";
    qInfo() << "test qInfo ";
    qCritical() <<"test qCritical ";
    return a.exec();
}
*/

#pragma once
//by karlchan cgs
#include <QDateTime>
#include <QFile>
#include <QTextStream>
#include <QApplication>
#include <QDebug>
#include <QDir>
#include <QMutex>
#include <QMutexLocker>

static int gIndex = 0;
//log日志，每个文件大小
static int SIZE_MAX_LOGSINGLEFILE  = 1024 * 1024 * 4;

class CLog
{
public:
    CLog();
    ~CLog();

public:
    static void InstallLog()
    {
        makesureDir();
        makesureIndex();
        qInstallMessageHandler(CLog::outputMessage);
    };
protected:

private:
    static void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
    {
        static QMutex mutex;
        QMutexLocker locker(&mutex);
        QString	strDir = QApplication::applicationDirPath() + "/../Log/" + QDateTime::currentDateTime().toString("yyyyMMdd");

        QString text;
        switch (type)
        {
        case QtWarningMsg:
            text = QString("[Warning]:");
            break;
        case QtInfoMsg:
        case QtDebugMsg:
            text = QString("[Info]:");
            break;
        case QtFatalMsg:
        case QtCriticalMsg:
            text = QString("[Error]:");
        }

        QString context_info = QString("[%1-%2]").arg(QString(context.file)).arg(context.line);
        QString current_date_time = QDateTime::currentDateTime().toString("[hh:mm:ss.z]");//yyyy-MM-dd
        QString current_date = QDateTime::currentDateTime().toString("yyyyMMdd");//z
        current_date += QString("_%1").arg(gIndex, 3, 10, QChar('0'));
        QString message = QString("%0%1%2 %3").arg(current_date_time).arg(context_info).arg(text).arg(msg);

        QString strPath = strDir + "/" + current_date + ".log";

        QFileInfo fi(strPath);
        if (fi.size() >= SIZE_MAX_LOGSINGLEFILE)
        {
            gIndex++;
            current_date = QDateTime::currentDateTime().toString("yyyyMMdd");//z
            current_date += QString("_%1").arg(gIndex, 3, 10, QChar('0'));
        }

        strPath = strDir + "/" + current_date + ".log";
        QFile file(strPath);
        if (file.open(QIODevice::WriteOnly | QIODevice::Append))
        {
            QTextStream text_stream(&file);
            text_stream << message << "\r\n";
            file.flush();
            file.close();
        }
    }
    static void makesureDir()
    {
        QString strDir;
        strDir = QApplication::applicationDirPath() + "/../Log/";
        QDir dir(strDir);
        if (!dir.exists())
        {
            dir.mkdir(strDir);
        }
        strDir = QApplication::applicationDirPath() + "/../Log/" + QDateTime::currentDateTime().toString("yyyyMMdd");
        dir.setPath(strDir);
        if (!dir.exists())
        {
            dir.mkdir(strDir);
        }
        qDebug()<<strDir;
    };
    static void makesureIndex()
    {
        QString	strDir = QApplication::applicationDirPath() + "/../Log/" + QDateTime::currentDateTime().toString("yyyyMMdd");
        QDir dir(strDir);
        dir.setFilter(QDir::Files | QDir::NoDotAndDotDot);
        QFileInfoList list = dir.entryInfoList();
        foreach (auto var,list)
        {
            QFileInfo fi(var.absoluteFilePath());
            if (fi.size() >= SIZE_MAX_LOGSINGLEFILE)
            {
                gIndex++;
            }
        }
    };
};

#endif // CLOG_H
